<?php

require_once('constants.php');

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    session_start();
    if (isset($_SESSION[FOLDER_NAME_VAR]) && isset($_SESSION[RESP_LAST_POSITION_VAR]) && isset($_SESSION[REQ_FILE_NAME_ARRAY]))
    {
        $foldername = $_SESSION[FOLDER_NAME_VAR];
        $lastpos = $_SESSION[RESP_LAST_POSITION_VAR];
        $respfilename = $foldername . RESP_FILE_NAME;
        $resplockfilename = $foldername . RESP_LOCK_FILE_NAME;
    }
    else
    {
        exit();
    }

    // Read all the response data from the file
    if (($resplock = fopen($resplockfilename, "r")) !== FALSE)
    {
        // Acquire the lock to ensure the read/write operations are atomic
        if (flock($resplock, LOCK_SH) === FALSE)
        {
            exit();
        }
        if (($respdata = file_get_contents($respfilename, FALSE, NULL, $lastpos)) !== FALSE)
        {
            if (!empty($respdata))
            {
                echo $respdata;
                $lastpos += strlen($respdata);
            }
            // Erase the content of response data file
            if ($lastpos > RESP_MAX_FILE_SIZE)
            {
                file_put_contents($respfilename, '');
                $lastpos = 0;
            }
            $_SESSION[RESP_LAST_POSITION_VAR] = $lastpos;
        }
        flock($resplock, LOCK_UN);
        fclose($resplock);
    }
    session_write_close();

    if (($data = file_get_contents("php://input")) !== FALSE)
    {
        if (!empty($data))
            arrange_requests($data);
    }
}

function arrange_requests($requests)
{
    // Write the request data to all the temp files
    foreach ($_SESSION[REQ_FILE_NAME_ARRAY] as $key => $reqfilename)
    {
        if (file_exists($reqfilename))
        {
            file_put_contents($reqfilename, $requests, FILE_APPEND | LOCK_EX);
        }
        else
        {
            unset($_SESSION[REQ_FILE_NAME_ARRAY][$key]);
        }
    }
}

?>